package com.java.comprehensive.design.building_modelling.singleton_pattern;

import cn.hutool.core.io.IoUtil;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 破坏单例 除了枚举之外 两只方式：序列化和反射
 */
public class BrokenRingTest {
    public static void main(String[] args) throws Exception {
        //通过 反序列化破环单例
        writeObjectFile();
        readObjectFile();

        //反射破环单例


        Class<SingletonDemo_5> demo_5Class = SingletonDemo_5.class;
        //获取无参构造对象
        Constructor<SingletonDemo_5> declaredConstructor = demo_5Class.getDeclaredConstructor();
        //需要访问检查
        declaredConstructor.setAccessible(true);
        SingletonDemo_5 singletonDemo_5 = declaredConstructor.newInstance();
        SingletonDemo_5 singletonDemo_51 = declaredConstructor.newInstance();
        System.out.println(singletonDemo_5 == singletonDemo_51);
        System.out.println(singletonDemo_5 == SingletonDemo_5.getInstance());


    }

    public static void readObjectFile() throws Exception {
        ObjectInputStream objectInputStream = new ObjectInputStream(Files.newInputStream(Paths.get("E:\\txt\\object.text")));
        SingletonDemo_5 singletonDemo_5 = (SingletonDemo_5) objectInputStream.readObject();
        System.out.println(singletonDemo_5.equals(SingletonDemo_5.getInstance()));
        IoUtil.close(objectInputStream);
    }

    public static void writeObjectFile() throws Exception {
        SingletonDemo_5 instance = SingletonDemo_5.getInstance();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(Files.newOutputStream(Paths.get("E:\\txt\\object.text")));
        objectOutputStream.writeObject(instance);
        IoUtil.close(objectOutputStream);
    }
}
